package com.runen.infinitemovement.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.runen.infinitemovement.R;
import com.runen.infinitemovement.alioss.OssUploadManager;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.PictrueEntity;
import com.runen.infinitemovement.model.entity.UserInformationEntity;
import com.runen.infinitemovement.picker.ConvertUtils;
import com.runen.infinitemovement.picker.DatePicker;
import com.runen.infinitemovement.picker.OptionPicker;
import com.runen.infinitemovement.picker.WheelView;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.tool.ScreenShotHelper;
import com.runen.infinitemovement.tool.UiUtil;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.PermissionUtils;
import com.runen.rxnetlibrary.utils.ToastUtils;
import com.runen.rxnetlibrary.utils.constant.PermissionConstants;
import com.runen.rxnetlibrary.utils.helper.DialogHelper;
import com.zhihu.matisse.Matisse;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PersonCenterActivity extends BaseActivity {

    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.top_btn_right)
    Button topBtnRight;
    @BindView(R.id.top_iv_right)
    ImageView topIvRight;
    @BindView(R.id.ci_head)
    RoundedCornersImage ciHead;
    @BindView(R.id.tv_nickName_title)
    TextView tvNickNameTitle;
    @BindView(R.id.tv_nickName)
    TextView tvNickName;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_age)
    TextView tvAge;
    @BindView(R.id.tv_signature_title)
    TextView tvSignatureTitle;
    @BindView(R.id.tv_signature)
    TextView tvSignature;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.tv_real_name)
    TextView tvRealName;
    @BindView(R.id.rv_real_name)
    RelativeLayout rvRealName;
    @BindView(R.id.rv_name)
    RelativeLayout rvName;
    @BindView(R.id.rl_sex)
    RelativeLayout rlSex;
    @BindView(R.id.tv_branch)
    TextView tvBranch;
    @BindView(R.id.rl_branch)
    RelativeLayout rlBranch;
    @BindView(R.id.rl_phone)
    RelativeLayout rlPhone;
    @BindView(R.id.rl_age)
    RelativeLayout rlAge;
    @BindView(R.id.rv_signature)
    RelativeLayout rvSignature;
    private List<Uri> avatar = new ArrayList<>();
    private int REQUEST_CODE_CHOOSE = 23;
    private String bucketName;
    /**
     * 图片名字
     */
    String imgFile;
    private OssUploadManager uploadManager;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_person_center;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        topTitle.setText("个人资料");
        uploadManager = new OssUploadManager(this);
        initData();
    }

    private void initData() {
        showDialog();
        new UserAPI().onGetUserInfo(null, new BaseResultCallback<UserInformationEntity>() {
            @Override
            public void onResponse(UserInformationEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    if (response.data != null) {
                        if (!TextUtils.isEmpty(response.data.headImgUrl + "?x-oss-process=image/resize,m_fill,w_144,h_144")) {
                            GlideUtils.loadImage(PersonCenterActivity.this, response.data.headImgUrl, ciHead);
                        }
                        tvNickName.setText(response.data.nickname);
                        if (response.data.sex == 0) {
                            tvSex.setText("女");
                        } else {
                            tvSex.setText("男");
                        }
                        tvPhone.setText(response.data.mobile);
                        tvAge.setText(response.data.birthday);
                        tvSignature.setText(response.data.introduce);
                        tvBranch.setText(response.data.departmentName);
                        tvRealName.setText(response.data.realName);
                    }
                }

            }
        });
    }

    @OnClick({R.id.top_btn_left, R.id.ci_head, R.id.rv_name, R.id.rl_sex, R.id.rl_phone, R.id.rl_age, R.id.rv_signature, R.id.rv_real_name})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.ci_head:
                onPermission();
                break;
            case R.id.rv_name:
                Intent intent = new Intent(PersonCenterActivity.this, EditUserInfoActivity.class);
                intent.putExtra("TITlE_NAME", "昵称");
                intent.putExtra("input_info", TextUtils.isEmpty(tvNickName.getText().toString()) ?"请输入昵称":tvNickName.getText().toString());
                startActivityForResult(intent, 99);
                break;
            case R.id.rl_sex:
                onSex();
                break;
            case R.id.rl_phone:
//                Intent intent3 = new Intent(PersonCenterActivity.this, EditUserInfoActivity.class);
//                intent3.putExtra("TITlE_NAME", "手机号码");
//                intent3.putExtra("input_info", "请输入手机号码");
//                startActivityForResult(intent3, 99);
                break;
            case R.id.rl_age:
                onBirthday();
                break;
            case R.id.rv_signature:
                Intent intent2 = new Intent(PersonCenterActivity.this, EditUserInfoActivity.class);
                intent2.putExtra("TITlE_NAME", "个性签名");
                intent2.putExtra("input_info", TextUtils.isEmpty(tvSignature.getText().toString()) ?"请输入个性签名":tvSignature.getText().toString());
                startActivityForResult(intent2, 99);
                break;
            case R.id.rv_real_name:
                Intent intent4 = new Intent(PersonCenterActivity.this, EditUserInfoActivity.class);
                intent4.putExtra("TITlE_NAME", "真实姓名");
                intent4.putExtra("input_info", TextUtils.isEmpty(tvRealName.getText().toString()) ? "请输入真实姓名" : tvRealName.getText().toString());
                startActivityForResult(intent4, 99);
                break;
        }
    }

    /**
     * 获取拍照权限
     */
    private void requestCamera() {
        UiUtil.getImageSelectorConfig(this, REQUEST_CODE_CHOOSE);
    }

    @SuppressLint("WrongConstant")
    private void onPermission() {
        //请求动态权限
        PermissionUtils.permission(
                PermissionConstants.STORAGE,
                PermissionConstants.CAMERA,
                PermissionConstants.WRITE_EXTERNAL_STORAGE,
                PermissionConstants.ACCESS_COARSE_LOCATION)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(final ShouldRequest shouldRequest) {
                        DialogHelper.showRationaleDialog(shouldRequest);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        requestCamera();
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever,
                                         List<String> permissionsDenied) {
                        if (!permissionsDeniedForever.isEmpty()) {
                            DialogHelper.showOpenAppSettingDialog();
                        }
                    }
                })
                .request();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 99) {
            if (data != null) {
                String userName = data.getStringExtra("USER_NAME");
                String realName = data.getStringExtra("REAL_NAME");
                String userSignature = data.getStringExtra("USER_SIGNATURE");
                if (!TextUtils.isEmpty(userName)) {
                    tvNickName.setText(userName);
                } else if (!TextUtils.isEmpty(realName)) {
                    tvRealName.setText(realName);
                } else if (!TextUtils.isEmpty(userSignature)) {
                    tvSignature.setText(userSignature);
                }
            }
        }
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            if (data != null) {
                avatar = Matisse.obtainResult(data);
                if (avatar != null && avatar.size() > 0) {
                    Log.e("OnActivityResult ", String.valueOf(avatar.get(0)));
                    GlideUtils.loadImage(this, avatar.get(0).toString(), ciHead);
                    File file = null;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                        file = CommonUtil.uriToFileApiQ(this, avatar.get(0));
                    } else {
                        file = CommonUtil.uri2File(this, avatar.get(0));
                    }
                    updateByImgUrl(file);
                }
            }
        }
    }

    private void updateByImgUrl(File imaUrl) {
        Log.e("OnActivityResult2 ", imaUrl.toString());
        TreeMap<String, String> mapType = new TreeMap<>();
        mapType.put("type", "headImg");
//        File file = ScreenShotHelper.compressImage2(CommonUtil.getImage(imaUrl.getPath()), this);
        TreeMap<String, File> mapFile = new TreeMap<>();
        mapFile.put("file", imaUrl);
        new UserAPI().putFile(mapType, mapFile, new BaseResultCallback<PictrueEntity>() {
            @Override
            public void onResponse(PictrueEntity response) {
                if (response.code == 0) {
                    if (response.data != null) {
                        Message message = new Message();
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        bundle.putString("headImgUrl", response.data.url);
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                }
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Bundle bundle = msg.getData();
                    String headUrl = bundle.getString("headImgUrl");
                    saveInfo(3, headUrl);
                    break;
            }
        }
    };

    /**
     * 性别
     */
    public void onSex() {
        final List<String> sexData = new ArrayList<>();
        sexData.add("男");
        sexData.add("女");
        OptionPicker picker = new OptionPicker((Activity) this, sexData);
        picker.setSubmitTextColor(CommonUtil.getColor(R.color.color_FFF8494A));
        picker.setCancelTextColor(CommonUtil.getColor(R.color.color_FFF8494A));
        picker.setTextColor(CommonUtil.getColor(R.color.color_FFF8494A));
        picker.setBackgroundResource(R.drawable.bg_white_6dp);
        WheelView.LineConfig config = new WheelView.LineConfig();
        config.setColor(CommonUtil.getColor(R.color.color_FFF8494A));//线颜色
        config.setAlpha(255);//线透明度
        //config.setRatio((float) (1.0 / 8.0));//线比率
        picker.setLineConfig(config);
        picker.setSelectedItem(tvSex.getText().toString());
        picker.setOffset(2);//偏移量
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                tvSex.setText(item);
                saveInfo(1, item);
            }
        });
        picker.show();
    }

    public void onBirthday() {
        onYearMonthDayPicker(tvAge);
    }

    /**
     * 年龄
     *
     * @param birth
     */
    public void onYearMonthDayPicker(TextView birth) {
        Calendar now = Calendar.getInstance();
        final DatePicker picker = new DatePicker(this);
        picker.setTopPadding(ConvertUtils.toPx(this, 10));
        picker.setRangeStart(1940, 1, 1);
        picker.setRangeEnd(now.get(Calendar.YEAR), (now.get(Calendar.MONTH) + 1), now.get(Calendar.DAY_OF_MONTH));
        picker.setTitleText("日期");
        picker.setTitleTextColor(CommonUtil.getColor(R.color.color_FFF8494A));
        picker.setSubmitText("确定");
        picker.setSubmitTextColor(CommonUtil.getColor(R.color.color_FFF8494A));
        picker.setCancelText("取消");
        picker.setTextColor(CommonUtil.getColor(R.color.color_FFF8494A));
        picker.setCancelTextColor(CommonUtil.getColor(R.color.color_FFF8494A));
        picker.setBackgroundResource(R.drawable.bg_white_6dp);
        WheelView.LineConfig lineConfig = new WheelView.LineConfig();
        lineConfig.setAlpha(255);//线透明度
        lineConfig.setColor(CommonUtil.getColor(R.color.color_FFF8494A));
        picker.setLineConfig(lineConfig);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                //保存出生日
                String ymd = year + "-" + month + "-" + day;
                birth.setText(ymd);
                saveInfo(2, ymd);
            }
        });
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });
        String str = "2000年01月01日";
        String s[] = str.split("(年|月|日)");
        picker.setSelectedItem(Integer.parseInt(s[0]), Integer.parseInt(s[1]), Integer.parseInt(s[2]));
        picker.show();
    }

    private void saveInfo(int flag, String info) {
        JSONObject object = new JSONObject();
        try {
            if (flag == 1) {
                if (info.equals("男")) {
                    object.put("sex", 1);
                } else {
                    object.put("sex", 0);
                }
                showDialog();
            } else if (flag == 2) {
                object.put("birthday", info);
                showDialog();
            } else if (flag == 3) {
                object.put("headImgUrl", info);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new UserAPI().onSavePerson(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                dismissDialog();
                if (response.getCode() == 0) {
                    ToastUtils.showShort(response.getMessage());
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
//                EventBus.getDefault().post(new EventBusEntity(5));
            }

            @Override
            public void onComplete() {
                super.onComplete();
            }
        });

    }

}